package com.uni.utils;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.uni.db.FileService;
import com.uni.domain.File;

public class FileUploader {

	public static boolean uploadFile(CommonsMultipartFile file, String path, String name, FileService dao){
		if (file == null) return false;
		if (file.isEmpty()) return false;
        File photo = new File();
        photo.setPath("photo");
        photo.setName(name);
        photo.setData(file.getBytes());
        System.out.println("content type = " + file.getContentType());
        photo.setContentType(file.getContentType());
        dao.saveFile(photo);
		return true;
	}
	
	public static int uploadFiles(Set<CommonsMultipartFile> files, String path, String name, FileService dao){
		int i = 0;
		for(CommonsMultipartFile file : files){
			if(uploadFile(file, path, name, dao)) i++;
		}
		return i;
	}
	
	@SuppressWarnings("unchecked")
	public static List<FileItem> parseRequest(HttpServletRequest request){
		try {
			ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
			if(!ServletFileUpload.isMultipartContent(request)){
				return new LinkedList<FileItem>();
			}
			List<FileItem> fileItemsList = servletFileUpload.parseRequest(request);
			Iterator<FileItem> iterator = fileItemsList.iterator();
			List<FileItem> files = new LinkedList<FileItem>();
			while (iterator.hasNext()){
			    FileItem param = (FileItem)iterator.next();
			    if(!param.isFormField()){
			    } else {
			    	System.out.println(param.getFieldName() + " => " + param.getString());
			    }
			}
			return files;
		} catch (org.apache.commons.fileupload.FileUploadException e) {
			e.printStackTrace();
		}
		return new LinkedList<FileItem>();
	}

	
}
